﻿using MQTTnet;
using MQTTnet.Protocol;
using MQTTnet.Server;
using MqttService.Controllers;
using System.Text;

namespace MqttService.Code
{
    public class MqttManager: IMqttManager
    {
        private readonly ILogger<MqttManager> _logger;
        private readonly IMqttInterface _mqttService;
        public MqttManager(ILogger<MqttManager> logger, IMqttInterface mqttService)
        {
            _logger = logger;
            _mqttService = mqttService;
        }
        public async Task PublishData(string topic, string data)
        {
            var message = new MqttApplicationMessage
            {
                Topic = topic,
                Payload = Encoding.Default.GetBytes(data),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce,
                Retain = true  // 服务端是否保留消息。true为保留，如果有新的订阅者连接，就会立马收到该消息。
            };

           await _mqttService._mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(message) // 发送消息给有订阅 topic_01的客户端
            {
                SenderClientId = "Server_01"
            });
        }
    }
}
